<?php
namespace app\common\model;
use think\Model;
use think\Cache;
class Story extends Model{
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
	// 自动完成
	protected $auto = [];
	protected $insert = ['story_addtime'];
	protected $update = [];	
	//自动获取
    public function getStoryIsendTextAttr($value,$data){
        $serialize = [0=>'连载',1=>'完结'];
        return $serialize[$data['story_isend']];
    }		
	//自动完成相关字段
	protected function setStoryAddtimeAttr($value,$data){
		if (!empty($data['story_checktime']) || empty($value)) {
			return time();
		}else{
			return strtotime($value);
		}
	}
	protected function setStoryContentAttr($value){
	    if(!empty($value)){
	       return zanpian_content_down_images(trim($value),'story');
	    }else{
	       return ""; 	 
	    }
	}
	protected function setStoryStatusAttr($value){
	    if(!empty($value)){
	       return $value;
	    }else{
	       return 1; 	 
	    }
	}	
    protected function setStoryPrtyAttr($value){
        if(!is_array($value)){
            return 0;
        }else{
            $attribute = 0;
            foreach ($value as $key=>$value){
                $attribute += $value;
            }
            return $attribute;
        }
    }		
	protected function setStoryNameAttr($value,$data){
		$part=db('part')->where(['part_vid'=>$data['story_vid'],'part_status'=>1])->order('part_id,part_oid')->column('part_name');
		if(!empty($part)){
			$end=end($part);
	        return $end; 
		}else{
			return "";
		}		   
	}
	protected function setStoryIsendAttr($value,$data){
	    if(!empty($value)){
	        return $value;
	    }else{
		    $part=db('part')->where(['part_vid'=>$data['story_vid'],'part_status'=>1])->order('part_oid asc')->field('part_name,part_title,part_content')->select();
		    $total=db('vod')->where('vod_id',$data['story_vid'])->value('vod_total');
		    $total=preg_replace('/\D/s', '',$total);
		    if(!empty($part)){
				$end=end($part);
				if(strstr($end['part_content'],"预告") || strstr($end['part_name'],"预告") || strstr($end['part_title'],"预告")){
					return 0;
				}
				elseif(($total==count($part) && strstr($end['part_content'],"剧终") || strstr($end['part_content'],"大结局")) || ($total==count($part) && strstr($end['part_name'],"剧终") || strstr($end['part_name'],"大结局"))|| ($total==count($part) && strstr($end['part_title'],"剧终") || strstr($end['part_title'],"大结局"))){
					return 1;
				}
	           return 0; 
		    }else{
			   return 0;
		    }		 
	    }
	}	
	protected function setStoryContinuAttr($value,$data){
		$part=db('part')->where(['part_vid'=>$data['story_vid'],'part_status'=>1])->order('part_id,part_oid')->count('part_id');
		if(!empty($part)){
				return $part; 
		}else{
			   return "";
		}		 
	}	
	protected function setStoryCidAttr($value,$data){
		if (!empty($value)) {
			return $value;
		}else{
			if(!empty($data['story_vid'])){
			    return model('channel')->get_type_cid(4,$data['story_vid']);
			}
			if(!empty($data['vod_id'])){
			    return model('channel')->get_type_cid(4,$data['vod_id']);
			}			
		}
	}	
	protected function setStoryKeywordsAttr($value,$data){
		if(!empty($value)){
			return $value;
		}elseif(empty($value) && !empty($data['story_vid']) && !empty($data['auto_keywords'])){
			$get=controller('get');
			$info=$get->keywords(db('vod')->where('vod_id',$data['story_vid'])->value('vod_name').'剧情',1);
			if($info['code']=1){
			    return $info['data']['str'];	
			}else{
				return '';
			}
		}else{
			return '';
		}
	}
	//事件注册
    protected static function init(){
		//写入后置事件
		Story::afterWrite(function ($story){
			if(!empty($story->story_id)){
			   model('Manage')->DelCache(4,$story->story_id);
			}
		});		
		//删除后置操作
        Story::afterDelete(function ($story){
			//删除关联分集
			if(!empty($story->story_vid)){	
			    $partid=db('part')->where('part_vid',$story->story_vid)->column('part_id');
		        model('part')->destroy($partid);
			}			
			zanpian_del_img_file($story['story_content']);
			model('Manage')->DelCache(4,$story->story_id);
       });	
    }	 	
	public function vod(){
		return $this->hasOne('vod','vod_id','story_vid');
    }	
   //关联相关表
	public function part(){
        return $this->hasMany('Part','part_vid','story_vid');
    }		
    public function homerole(){
        return $this->hasMany('Role','role_vid','story_vid')->where('role_status',1)->order('role_oid asc');
    }
	public function homeactor(){
		return $this->hasOne('actor','actor_vid','story_vid')->where('actor_status',1);
    }
	public function homevod(){
		return $this->hasOne('vod','vod_id','story_vid')->where('vod_status',1);
    }		
	public function story_data(){
	   $data = input('post.');
	   $rs=model('Story');
	   if(empty($data['story_vid'])){
	      $data['story_vid']=$data['vod_id'];
	   }
	   if(!empty($data['story_title']) || !empty($data['story_keywords']) || !empty($data['story_description']) || !empty($data['story_reurl']) || !empty($data['story_content'])){
			if($data['story_id']){
			$rs->save($data, array('story_id' => $data['story_id']));
			}elseif($data['vod_id']){
				$info=$rs->where('story_vid',$data['vod_id'])->value('story_id');
				if($info){
			    $rs->save($data, array('story_vid' => $data['vod_id']));
				}else{
					$data['story_vid']=$data['vod_id'];
					$rs->save($data);
				}
			}else{
			    $rs->save($data);
		    }
	   }
	}	
 	//剧情
	public function vod_story($params,$where){
			if(!empty($params['cache_name']) && !empty($params['cache_time'])){
			 $data_cache_content = cache($params['cache_name']);
			  if($data_cache_content){
				return $data_cache_content;
			  }
		    }
		    $data=$this->where($where)->find();
			$array_story=$data->toArray();
			$vod_letters=get_vod_info($array_story['story_vid'],'vod_id','vod_letters');
			if(!empty($array_story['story_content'])){//如果存在剧情
			$array_story['story_readurl']=zanpian_data_url('home/story/read',array('id'=>$array_story['story_id'],'pinyin'=>$vod_letters,'cid'=>$array_story['story_cid'],'dir'=>getlistname($array_story['story_cid'],'list_dir')));
			$array_story['story_content']=$array_story['story_content'];
			$listarray=explode('||',$array_story['story_content']); //将每一集分组
			//krsort($listarray);	//	倒叙排列
			foreach($listarray as $key=>$jiinfo){
				$jiinfoarray=explode('@@',$jiinfo);
				$arrays['story_list'][$key+1]['story_name']=$jiinfoarray[0];
				$arrays['story_list'][$key+1]['story_title']=$jiinfoarray[1];
				$arrays['story_list'][$key+1]['story_info']=$jiinfoarray[2];
				if($key+1==1){
				$arrays['story_list'][$key+1]['story_readurl']=zanpian_data_url('home/story/read',array('id'=>$array_story['story_id'],'pinyin'=>$vod_letters,'cid'=>$array_story['story_cid'],'dir'=>getlistname($array_story['story_cid'],'list_dir')));
				}else{
				$arrays['story_list'][$key+1]['story_readurl']=str_replace('{!page!}',$jinum,zanpian_data_url('home/story/read',array('id'=>$array_story['story_id'],'pinyin'=>$array['vod_letters'],'cid'=>$array_story['story_cid'],'dir'=>getlistname($array_story['story_cid'],'list_dir'),'p'=>$key+1)));		
				}
			}
			$array_story['story_list']=$arrays['story_list'];
			unset($array_story['story_content']);
			if(!empty($params['cache_name']) && !empty($params['cache_time'])){
			cache($params['cache_name'],$array_story, intval($params['cache_time']) );
	        }
			return $array_story;	
		}
	else{
		return false;
		}
	}

    public function listData($tag){
		$param = zanpiancms_param_url();
		if(!is_array($tag)) {
            $tag=json_decode($tag, true);
        }
		$tag['field']= !empty($tag['field']) ? $tag['field'] : '*,vod_id,vod_cid,vod_mcid,vod_name,vod_aliases,vod_title,vod_color,vod_actor,vod_director,vod_content,vod_pic,vod_bigpic,vod_diantai,vod_tvcont,vod_area,vod_language,vod_year,vod_continu,vod_total,vod_isend,vod_addtime,vod_hits,vod_hits_day,vod_hits_week,vod_hits_month,vod_hits_lasttime,vod_stars,vod_up,vod_down,vod_play,vod_gold,vod_golder,vod_isfilm,vod_filmtime,vod_length,vod_weekday,vod_letters,vod_bigpic,vod_label,vod_jumpurl,actor_id,actor_cid';
		$tag['limit']= !empty($tag['limit']) ? $tag['limit'] : 10;
		if(!empty($tag['page']) && !empty($param['order'])){
			$tag['order']='story_'.$param['order'].' desc';
		}			
		if(empty(order_check($tag['order']))){
			$tag['order']='story_addtime desc';
		}		
		$cahce=tag_cache($tag);
	    //优先从缓存调用数据及分页变量
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){			
			$data_cache_content = Cache::get($cahce['cache_name']);
			if($data_cache_content){
				return $data_cache_content;
			}
		}		
		$where=[];
		$where['story_status']=['eq',1];
		$where['vod_status']=['eq',1];
	    if(!empty($tag['ids'])){
		     $where['story_id'] = array('in',$tag['ids']);
	    }
	    if(!empty($tag['vid'])){
		     $where['story_vid'] = array('in',$tag['vid']);
	    }		
	    if(!empty($tag['not'])){
		     $where['story_id'] = array('not in',$tag['not']);
	    }
	    if(!empty($tag['vnot'])){
		     $where['story_vid'] = array('not in',$tag['vnot']);
	    }		
	    if (!empty($tag['letter'])) {
		    $letter = explode(',',$tag['letter']);
		    if(count($letter)>1) {
			    $where['vod_letter'] = array('in',$tag['letter']);
		    }else{
			    $where['vod_letter'] = array('eq',$letter[0]);
		    }
	    }		
	    if(!empty($tag['cid'])) {
		    $cids = explode(',',trim($tag['cid']));
		    if(count($cids) > 1) {
			    $where['story_cid'] = array('in',getlistarr_tag($cids));
		    }else{
			     $where['story_cid'] = getlistsqlin($tag['cid']);
		    }
	    }
	    if(!empty($tag['vcid'])) {
		    $cids = explode(',',trim($tag['vcid']));
		    if(count($cids) > 1) {
			    $where['vod_cid'] = array('in',getlistarr_tag($cids));
		    }else{
			     $where['vod_cid'] = getlistsqlin($tag['vcid']);
		    }
	    }		
	    if(!empty($tag['stars'])) {
		     $where['story_stars'] = array('in',$tag['stars']);
	    }
	    if(!empty($tag['vstars'])) {
		     $where['vod_stars'] = array('in',$tag['vstars']);
	    }		
	    if (!empty($tag['hits'])) {
		    $hits = explode(',',$tag['hits']);
		    if (count($hits) > 1) {
			    $where['story_hits'] = array('between',$hits[0].','.$hits[1]);
		    }else{
			    $where['story_hits'] = array('gt',$hits[0]);
		    }
	    }
	    if (!empty($tag['vhits'])) {
		    $hits = explode(',',$tag['vhits']);
		    if (count($hits) > 1) {
			    $where['vod_hits'] = array('between',$hits[0].','.$hits[1]);
		    }else{
			    $where['vod_hits'] = array('gt',$hits[0]);
		    }
	    }		
	    if(!empty($tag['name'])) {
		    $where['vod_name'] = array('like','%'.$tag['name'].'%');	
	    }
	    if(!empty($tag['wd'])) {
		    $where['vod_name'] = array('like','%'.$tag['wd'].'%');	
	    }
        if(!empty($tag['gold'])) {
		    $gold = explode(',',$tag['gold']);
		    if(count($gold) > 1) {
			    $where['story_gold'] = array('between',$gold[0].','.$gold[1]);
		    }else{
			    $where['story_gold'] = array('gt',$gold[0]);
		    }
	    }
        if(!empty($tag['vgold'])) {
		    $gold = explode(',',$tag['vgold']);
		    if(count($gold) > 1) {
			    $where['vod_gold'] = array('between',$gold[0].','.$gold[1]);
		    }else{
			    $where['vod_gold'] = array('gt',$gold[0]);
		    }
	    }		
	    if(!empty($tag['golder'])) {
		    $golder = explode(',',$tag['golder']);
		    if(count($golder) > 1) {
			    $where['story_golder'] = array('between',$golder[0].','.$golder[1]);
		    }else{
			    $where['story_golder'] = array('gt',$golder[0]);
		    }
	    }
	    if(!empty($tag['vgolder'])) {
		    $golder = explode(',',$tag['vgolder']);
		    if(count($golder) > 1) {
			    $where['vod_golder'] = array('between',$golder[0].','.$golder[1]);
		    }else{
			    $where['vod_golder'] = array('gt',$golder[0]);
		    }
	    }		
	    if(!empty($tag['up'])) {
		    $up = explode(',',$tag['up']);
		    if(count($up)>1) {
			    $where['story_up'] = array('between',$up[0].','.$up[1]);
		    }else{
			    $where['story_up'] = array('gt',$up[0]);
		    }
	    }
	    if(!empty($tag['vup'])) {
		    $up = explode(',',$tag['vup']);
		    if(count($up)>1) {
			    $where['vod_up'] = array('between',$up[0].','.$up[1]);
		    }else{
			    $where['vod_up'] = array('gt',$up[0]);
		    }
	    }		
	    if(!empty($tag['down'])) {
		    $down = explode(',',$tag['down']);
		    if(count($down)>1) {
			    $where['story_down'] = array('between',$down[0].','.$down[1]);
		    }else{
			    $where['story_down'] = array('gt',$down[0]);
		    }
	    }
	    if(!empty($tag['vdown'])) {
		    $down = explode(',',$tag['vdown']);
		    if(count($down)>1) {
			    $where['vod_down'] = array('between',$down[0].','.$down[1]);
		    }else{
			    $where['vod_down'] = array('gt',$down[0]);
		    }
	    }		
        if(!empty($tag['addtime'])){
		    $time = explode(',',$tag['addtime']);
		    if(count($time) > 1) {
			    $where['story_addtime'] = array('between',intval(strtotime($time[0])).','.intval(strtotime($time[1])));
		    }else{
			    $where['story_addtime'] = array('gt',intval(strtotime($time[0])));
		    }			
        }
        if(!empty($tag['vaddtime'])){
		    $time = explode(',',$tag['vaddtime']);
		    if(count($time) > 1) {
			    $where['vod_addtime'] = array('between',intval(strtotime($time[0])).','.intval(strtotime($time[1])));
		    }else{
			    $where['vod_addtime'] = array('gt',intval(strtotime($time[0])));
		    }			
        }
	    if(!empty($tag['filmtime'])){
			if($tag['filmtime']==1){
		        //$where['vod_filmtime'] = array('between',array(strtotime("-6 month",time()),time()));
				$where['vod_filmtime'] = array('elt',time());
			}else{
				$tjinfo=explode('|',trim($tag['filmtime']));
			    if($tjinfo[1]){
				    $where['vod_filmtime'] = array('between',array(intval($tjinfo[0]),intval($tjinfo[1])));
			    }else{
		            $where['vod_filmtime'] = array('gt', time());
			    }
			}
	    }
	    if(!empty($tag['tj'])){
		    $tjinfo=explode('|',trim($tag['tj']));
		    if($tjinfo[3]){
			    $where[$tjinfo[3]] = array($tjinfo[1],$tjinfo[2]);
		    }else{
			    $where[$tjinfo[0]] = array($tjinfo[1],$tjinfo[2]);
		    }
	    }
	    if (!empty($tag['diantai'])) {
		    $where['vod_diantai'] = array('neq','');
	    }			
		if($tag['prty']){
			if(!empty(check_position($tag['prty']))){
			    $where['story_prty'] = check_position($tag['prty']);
			}
		}
		if($tag['vprty']){
			if(!empty(check_position($tag['vprty']))){
			    $where['vod_prty'] = check_position($tag['vprty']);
			}
		}		
        if(!empty($tag['page'])){
			$count=db('story')->join('vod vod','vod.vod_id =story_vid')->where($where)->count('story_id');
		    $data = db('story')->join('vod vod','vod.vod_id =story_vid','LEFT')->join('actor actor','actor.actor_vid =story_vid','LEFT')->join('part part','part.part_oid = story_continu and part.part_vid = story_vid','LEFT')->where($where)->field($tag['field'])->order($tag['order'])->paginate($tag['limit'],$count);
		}else{
			$data = db('story')->join('vod vod','vod.vod_id =story_vid','LEFT')->join('actor actor','actor.actor_vid =story_vid','LEFT')->join('part part','part.part_oid = story_continu and part.part_vid = story_vid','LEFT')->where($where)->field($tag['field'])->order($tag['order'])->limit($tag['limit'])->select();
		}
		if(!empty($cahce['cache_name']) && !empty($cahce['cache_time'])){
			cache::tag('foreach_story')->set($cahce['cache_name'],$data,intval($cahce['cache_time'])); 
	    }
		return $data;
    }   	
}
// +----------------------------------------------------------------------
// | ZanPianCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.zanpian.com All rights reserved.
// +----------------------------------------------------------------------
// | BBS:  <http://www.feifeicms.cc>
// +----------------------------------------------------------------------